package com.moorror.codegenvel.view.window.codegenxrender;

import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.project.Project;
import com.intellij.util.concurrency.NonUrgentExecutor;
import com.moorror.codegenvel.common.select.MRMultiSelect;
import com.moorror.codegenvel.common.textfield.SearchKeywordFunAction;
import com.moorror.codegenvel.common.tree.AbstractMTTreePanel;
import com.moorror.codegenvel.db.sqlite.dao.impl.CodeGenXRenderConnectDaoImpl;
import com.moorror.codegenvel.db.sqlite.entity.CodeGenXRenderConnect;
import com.moorror.codegenvel.utils.TreeCellEntityUtils;
import com.moorror.codegenvel.view.component.AbstractCodeGenByVelocitySetTab;
import com.moorror.codegenvel.view.window.codegenxrender.tree.MTTreeCellCodeGenXRenderRoot;

import javax.swing.tree.DefaultTreeModel;
import java.util.List;

/**
 * @Author jiyanghuang
 * @Date 2024/4/11 23:13
 * https://plugins.jetbrains.com/docs/marketplace/obfuscate-the-plugin.html
 */
public class CodeGenXRenderLeft extends AbstractMTTreePanel {

    public static final String SHOW_RIGHT_PANEL = "showRightPanel";
    public static final String SHOW_SEQUENcE_ROOT = "showSequenceRoot";

    private MRMultiSelect multiSelect;

    private boolean searchProcessing = false;

    public CodeGenXRenderLeft(Project project, AbstractCodeGenByVelocitySetTab abstractToolSetTab) {
        super(project, false, new MTTreeCellCodeGenXRenderRoot(project), abstractToolSetTab);
    }

    @Override
    protected void addActions(DefaultActionGroup actionGroup) {
        SearchKeywordFunAction searchKeywordFunAction = new SearchKeywordFunAction(this, this::querySqliteWrap);
        actionGroup.add(searchKeywordFunAction);
    }

    public boolean querySqliteWrap(String searchText) {
        if (searchProcessing) {
            return true;
        }
        searchProcessing = true;
        ReadAction.nonBlocking(() -> {
            querySqlite(searchText);
            return null;
        }).finishOnUiThread(ModalityState.NON_MODAL, (c) -> {
            ((DefaultTreeModel) jTree().getModel()).reload(rootTreeNode);
            searchProcessing = false;
        }).inSmartMode(project).submit(NonUrgentExecutor.getInstance());
        return true;
    }

    public void querySqlite(String searchText) {
        List<CodeGenXRenderConnect> codeGenScenes = CodeGenXRenderConnectDaoImpl.getInstance().searchLikeOneTMTM(searchText);
        TreeCellEntityUtils.genTreeRoot(rootTreeNode, project, codeGenScenes);
    }
}
